const 
	fs = require('fs'),
	_ = require('lodash'),
	uuid = require('uuid/v1'),
	request = require('superagent');

require('superagent-proxy')(request);
	
module.exports = async function(self, cmd, ...args){
	switch(cmd){
		case 'add':
			if (args.length>0) {
				if (_.find(self.namespace.flags, {flag: args[0]}))
					console.error('already exists.');
				else
					self.namespace.flags.push({id: uuid(), flag: args[0], time: new Date()});
			}
			break;
		case 'del':
			if (args.length>0) {
				_.remove(self.namespace.flags, item => {return item.id === args[0] || item.flag === args[0]});
			}
			break;
		case 'clear':
			self.namespace.flags = [];
			break;
		case 'url':
			self.namespace.flagurl = args[0];
			console.log(self.namespace.flagurl);
			break;
		case 'get':
			self.rl.write('batrun\n');
			break;
		case 'load':
			self.namespace.flags = JSON.parse(fs.readFileSync('./flags.json').toString());
			break;
		case 'submit':
			if (self.namespace.flagurl === '' || self.namespace.token === '') {
				console.error('flag url or token not set');
				return;
			}
			console.log('start submitt...');
			for(let flag of self.namespace.flags) {
				if (!flag.submitted) {
					process.stdout.write(flag.flag);
					await request.post(self.namespace.submitflagurl)
						//.proxy('http://127.0.0.1:8888')
						.send({
							token: self.namespace.token,
							flag: flag.flag
						})
						.then(res => {
							// set flag submitted
							console.log(' OK'.green.bold);
							if (res.ok) flag.submitted = true;
						})
						.catch(err => {
							console.log(' ' + err.message.red.bold);
						})
				}
			}
			break;
		default:
			console.log(self.namespace.flags);
			break;
	}
}